package com.trace.demo.controller;

import com.trace.demo.entity.DistributionRecord;
import com.trace.demo.entity.Product;
import com.trace.demo.entity.User;
import com.trace.demo.repository.DistributionRecordRepository;
import com.trace.demo.repository.ProductRepository;
import com.trace.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 分销分析控制器
 */
@RestController
@RequestMapping("/api/distribution-analysis")
public class DistributionAnalysisController {

    private static final Logger logger = LoggerFactory.getLogger(DistributionAnalysisController.class);

    private final ProductRepository productRepository;
    private final UserRepository userRepository;
    
    // 可选依赖
    private DistributionRecordRepository distributionRecordRepository;

    @Autowired
    public DistributionAnalysisController(ProductRepository productRepository,
                                         UserRepository userRepository) {
        this.productRepository = productRepository;
        this.userRepository = userRepository;
        logger.info("DistributionAnalysisController initialized with required dependencies");
    }
    
    @Autowired(required = false)
    public void setDistributionRecordRepository(DistributionRecordRepository distributionRecordRepository) {
        this.distributionRecordRepository = distributionRecordRepository;
        logger.info("DistributionRecordRepository injected");
    }

    /**
     * 获取用户的分销数据分析
     * @param userId 用户ID
     * @return 分销数据分析
     */
    @GetMapping("/user/{userId}")
    public ResponseEntity<?> getUserDistributionAnalysis(@PathVariable Long userId) {
        try {
            if (distributionRecordRepository == null) {
                return ResponseEntity.ok(Collections.singletonMap("message", "Distribution analysis not available"));
            }
            
            return userRepository.findById(userId)
                .map(user -> {
                    Map<String, Object> result = new HashMap<>();

                    // 获取用户总的分销记录数
                    long totalDistributions = distributionRecordRepository.countByDistributorId(userId);
                    result.put("totalDistributions", totalDistributions);

                    // 获取分销总额
                    double totalAmount = distributionRecordRepository.findByDistributorId(userId)
                        .stream()
                        .mapToDouble(DistributionRecord::getAmount)
                        .sum();
                    result.put("totalAmount", totalAmount);

                    // 获取分销的产品类别统计
                    List<DistributionRecord> records = distributionRecordRepository.findByDistributorId(userId);
                    Map<String, Long> categoryStats = new HashMap<>();

                    for (DistributionRecord record : records) {
                        if (record.getProduct() != null) {
                            String category = record.getProduct().getCategory();
                            categoryStats.put(category, categoryStats.getOrDefault(category, 0L) + 1);
                        }
                    }
                    result.put("categoryStats", categoryStats);

                    // 最近7天的分销趋势
                    LocalDateTime sevenDaysAgo = LocalDateTime.now().minusDays(7);
                    List<DistributionRecord> recentRecords = distributionRecordRepository
                        .findByDistributorIdAndCreatedAtAfter(userId, sevenDaysAgo);

                    Map<String, Object> dailyStats = new LinkedHashMap<String, Object>();
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd");

                    for (int i = 0; i < 7; i++) {
                        LocalDate date = LocalDate.now().minusDays(i);
                        String formattedDate = date.format(formatter);

                        final LocalDate compareDate = date;
                        long count = recentRecords.stream()
                            .filter(r -> r.getCreatedAt().toLocalDate().equals(compareDate))
                            .count();

                        dailyStats.put(formattedDate, count);
                    }
                    result.put("dailyTrend", dailyStats);

                    return ResponseEntity.ok(result);
                })
                .orElse(ResponseEntity.badRequest().body(createErrorMap("User not found with id: " + userId)));
        } catch (Exception e) {
            logger.error("Error fetching distribution analysis: {}", e.getMessage(), e);
            Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("error", "Error fetching distribution analysis: " + e.getMessage());
            return ResponseEntity.badRequest().body(errorMap);
        }
    }

    /**
     * 获取产品的分销数据分析
     * @param productId 产品ID
     * @return 分销数据分析
     */
    @GetMapping("/product/{productId}")
    public ResponseEntity<?> getProductDistributionAnalysis(@PathVariable Long productId) {
        try {
            if (distributionRecordRepository == null) {
                return ResponseEntity.ok(Collections.singletonMap("message", "Distribution analysis not available"));
            }
            
            return productRepository.findById(productId)
                .map(product -> {
                    Map<String, Object> result = new HashMap<>();

                    // 获取产品总的分销记录数
                    long totalDistributions = distributionRecordRepository.countByProductId(productId);
                    result.put("totalDistributions", totalDistributions);

                    // 获取分销总额
                    double totalAmount = distributionRecordRepository.findByProductId(productId)
                        .stream()
                        .mapToDouble(DistributionRecord::getAmount)
                        .sum();
                    result.put("totalAmount", totalAmount);

                    // 获取分销者统计信息
                    List<DistributionRecord> records = distributionRecordRepository.findByProductId(productId);
                    Map<Long, Long> distributorStats = records.stream()
                        .collect(Collectors.groupingBy(r -> r.getDistributor().getId(), Collectors.counting()));

                    List<Map<String, Object>> distributors = new ArrayList<>();
                    for (Map.Entry<Long, Long> entry : distributorStats.entrySet()) {
                        User distributor = userRepository.findById(entry.getKey()).orElse(null);
                        if (distributor != null) {
                            Map<String, Object> distributorInfo = new HashMap<>();
                            distributorInfo.put("id", distributor.getId());
                            distributorInfo.put("name", distributor.getUsername());
                            distributorInfo.put("count", entry.getValue());
                            distributors.add(distributorInfo);
                        }
                    }
                    result.put("distributors", distributors);

                    // 最近7天的分销趋势
                    LocalDateTime sevenDaysAgo = LocalDateTime.now().minusDays(7);
                    List<DistributionRecord> recentRecords = distributionRecordRepository
                        .findByProductIdAndCreatedAtAfter(productId, sevenDaysAgo);

                    Map<String, Object> dailyStats = new LinkedHashMap<String, Object>();
                    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd");

                    for (int i = 0; i < 7; i++) {
                        LocalDate date = LocalDate.now().minusDays(i);
                        String formattedDate = date.format(formatter);

                        final LocalDate compareDate = date;
                        long count = recentRecords.stream()
                            .filter(r -> r.getCreatedAt().toLocalDate().equals(compareDate))
                            .count();

                        dailyStats.put(formattedDate, count);
                    }
                    result.put("dailyTrend", dailyStats);

                    return ResponseEntity.ok(result);
                })
                .orElse(ResponseEntity.badRequest().body(createErrorMap("Product not found with id: " + productId)));
        } catch (Exception e) {
            logger.error("Error fetching distribution analysis: {}", e.getMessage(), e);
            Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("error", "Error fetching distribution analysis: " + e.getMessage());
            return ResponseEntity.badRequest().body(errorMap);
        }
    }

    /**
     * 创建分销记录
     *
     * @return 创建的分销记录
     */
    @PostMapping("/record")
    public ResponseEntity<?> createDistributionRecord(@RequestBody Map<String, Object> recordData) {
        try {
            if (distributionRecordRepository == null) {
                return ResponseEntity.badRequest().body(Collections.singletonMap("error", "Distribution record service not available"));
            }
            
            Long distributorId = Long.valueOf(recordData.get("distributorId").toString());
            Long productId = Long.valueOf(recordData.get("productId").toString());
            Double amount = Double.valueOf(recordData.get("amount").toString());

            Optional<User> distributorOpt = userRepository.findById(distributorId);
            Optional<Product> productOpt = productRepository.findById(productId);

            if (!distributorOpt.isPresent()) {
                Map<String, Object> errorMap = new HashMap<>();
                errorMap.put("error", "Distributor not found");
                return ResponseEntity.badRequest().body(errorMap);
            }

            if (!productOpt.isPresent()) {
                Map<String, Object> errorMap = new HashMap<>();
                errorMap.put("error", "Product not found");
                return ResponseEntity.badRequest().body(errorMap);
            }

            DistributionRecord record = new DistributionRecord();
            record.setDistributor(distributorOpt.get());
            record.setProduct(productOpt.get());
            record.setAmount(amount);
            record.setCreatedAt(LocalDateTime.now());

            // 设置其他属性
            if (recordData.containsKey("quantity")) {
                record.setQuantity(Integer.valueOf(recordData.get("quantity").toString()));
            }

            if (recordData.containsKey("customerId") && recordData.get("customerId") != null) {
                Long customerId = Long.valueOf(recordData.get("customerId").toString());
                userRepository.findById(customerId).ifPresent(record::setCustomer);
            }

            DistributionRecord savedRecord = distributionRecordRepository.save(record);
            return ResponseEntity.ok(savedRecord);
        } catch (Exception e) {
            logger.error("Error creating distribution record: {}", e.getMessage(), e);
            Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("error", "Error creating distribution record: " + e.getMessage());
            return ResponseEntity.badRequest().body(errorMap);
        }
    }

    /**
     * 获取系统范围的分销统计
     * @return 分销统计
     */
    @GetMapping("/system-stats")
    public ResponseEntity<?> getSystemDistributionStats() {
        try {
            if (distributionRecordRepository == null) {
                return ResponseEntity.ok(Collections.singletonMap("message", "Distribution statistics not available"));
            }
            
            Map<String, Object> result = new HashMap<>();

            // 总分销数量
            long totalRecords = distributionRecordRepository.count();
            result.put("totalRecords", totalRecords);

            // 总分销金额
            double totalAmount = distributionRecordRepository.findAll()
                .stream()
                .mapToDouble(DistributionRecord::getAmount)
                .sum();
            result.put("totalAmount", totalAmount);

            // 按产品类别统计分销数量
            List<DistributionRecord> allRecords = distributionRecordRepository.findAll();
            Map<String, Long> categoryStats = new HashMap<>();
            for (DistributionRecord record : allRecords) {
                if (record.getProduct() != null) {
                    String category = record.getProduct().getCategory();
                    categoryStats.put(category, categoryStats.getOrDefault(category, 0L) + 1);
                }
            }
            result.put("categoryStats", categoryStats);

            // 近30天的分销趋势
            LocalDateTime thirtyDaysAgo = LocalDateTime.now().minusDays(30);
            List<DistributionRecord> recentRecords = distributionRecordRepository.findByCreatedAtAfter(thirtyDaysAgo);

            Map<String, Object> dailyStats = new LinkedHashMap<String, Object>();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MM-dd");

            for (int i = 29; i >= 0; i--) {
                LocalDate date = LocalDate.now().minusDays(i);
                String formattedDate = date.format(formatter);

                final LocalDate compareDate = date;
                long count = recentRecords.stream()
                    .filter(r -> r.getCreatedAt().toLocalDate().equals(compareDate))
                    .count();

                dailyStats.put(formattedDate, count);
            }
            result.put("dailyTrend", dailyStats);

            // 最活跃的分销商TOP5
            Map<Long, Long> distributorStats = allRecords.stream()
                .collect(Collectors.groupingBy(r -> r.getDistributor().getId(), Collectors.counting()));

            List<Map.Entry<Long, Long>> topDistributors = distributorStats.entrySet().stream()
                .sorted(Map.Entry.<Long, Long>comparingByValue().reversed())
                .limit(5)
                .collect(Collectors.toList());

            List<Map<String, Object>> distributorList = new ArrayList<>();
            for (Map.Entry<Long, Long> entry : topDistributors) {
                User distributor = userRepository.findById(entry.getKey()).orElse(null);
                if (distributor != null) {
                    Map<String, Object> distributorInfo = new HashMap<>();
                    distributorInfo.put("id", distributor.getId());
                    distributorInfo.put("name", distributor.getUsername());
                    distributorInfo.put("count", entry.getValue());
                    distributorList.add(distributorInfo);
                }
            }
            result.put("topDistributors", distributorList);

            return ResponseEntity.ok(result);
        } catch (Exception e) {
            logger.error("Error fetching system distribution stats: {}", e.getMessage(), e);
            Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("error", "Error fetching system distribution stats: " + e.getMessage());
            return ResponseEntity.badRequest().body(errorMap);
        }
    }

    private Map<String, Object> createErrorMap(String errorMessage) {
        Map<String, Object> errorMap = new HashMap<>();
        errorMap.put("error", errorMessage);
        return errorMap;
    }
}
